package com.gonsin.easycount.bus;

import com.gonsin.easycount.model.CountGetter;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 事件总线
 */
public class EasyBus {

    private static EasyBus instance;

    public static EasyBus getInstance(){
        if(instance == null){
            instance = new EasyBus();
        }
        return instance;
    }

    private Map<String, Set<OptionListener>> listenerMap = new ConcurrentHashMap<>();


    /**
     * 触发事件
     */
    public void notifyOptionChanged(String topic, CountGetter countGetter){
        Set<OptionListener> listeners = listenerMap.computeIfAbsent(topic, k -> new HashSet<>());
        Set<OptionListener> temp = new HashSet<>(listeners);
        for(OptionListener listener : temp){
            try {
                listener.onCountChanged(countGetter);
            } catch (Exception ex){
                ex.printStackTrace();
            }
        }
    }

    public void registerOptionListener(String topic, OptionListener listener) {
        Set<OptionListener> listeners = listenerMap.computeIfAbsent(topic, k -> new HashSet<>());
        listeners.add(listener);
    }

    public void unregisterOptionListener(String topic){
        listenerMap.remove(topic);
//        Set<OptionListener> listeners = listenerMap.computeIfAbsent(topic, k -> new HashSet<>());
//        listeners.remove(listener);
//        if(listeners.isEmpty()){
//            listenerMap.remove(topic);
//        }
    }
}
